import { isError, isString } from "lodash";

export type Response = {
  success?: boolean | null | void;
  code?: number | null | void;
  msg?: string | null | void;
}
export class KnownError extends Error {
  readonly code: string;
  readonly reply: any;
  constructor(code: string, msg: string, reply?: any) {
    super(msg)
    this.code = code;
    this.reply = reply;
  }

  /**
   * 判断一个值是否是KnownError
   * 
   * @todo instanceof KnownError 存在判断不正确的情况，需用此函数。
   * @param {*} v
   * @returns {v is KnownError}
   */
  static is = (v: any): v is KnownError => {
    return isError(v) && isString((v as any).code);
  }
}
export function checkReply<R extends Response>(reply?: R | null): R {
  if (!reply)
    throw new Error(`服务异常，返回数据为${JSON.stringify(reply)}`)
  if ((reply.code != 0 && reply.code != 200) || !reply.success)
    throw new KnownError('' + reply.code, reply.msg || '服务异常', reply)
  return reply;
}